package com.zz.study.sharding.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
 * 并发工具类
 * created by xjx on  2023-11-16 11:07
 */
@Slf4j
public class ConcurrentUtil {

    /**
     * 执行任务
     *
     * @param taskExecutor ThreadPoolTaskExecutor
     * @param callable 回调
     * @param <T> 返回的结果集Future泛型
     * @return Future泛型
     */
    public static <T> Future<T> doJob(ThreadPoolTaskExecutor taskExecutor, Callable<T> callable) {
        return taskExecutor.submit(callable);
    }

    public static void doJob(ThreadPoolTaskExecutor taskExecutor, Runnable runnable) {
         taskExecutor.submit(runnable);
    }

    /**
     * 获取结果集，执行时会阻塞直到有结果，中间的异常不会被静默
     *
     * @param future Future
     * @param <T> 返回的结果集泛型
     * @return T
     */
    public static <T> T futureGet(Future<T> future) {
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}


